package cn.nawang.ebeim.api.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

/**
 * @ClassName: SimpleCORSFilter
 * @Description: TODO
 * @author fanyb
 * @date Sep 21, 2015 1:59:29 PM
 * @version v1.0
 */
@Component
public class SimpleCORSFilter implements Filter {
  protected String origin;
  protected String methods;
  protected String age;
  protected String headers;
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    /* 表明它允许所有发起跨域请求  */
    response.setHeader("Access-Control-Allow-Origin", origin);
    /* 表明它允许GET、PUT、DELETE、OPTIONS的外域请求 */
    response.setHeader("Access-Control-Allow-Methods", methods);
    /* 表明在3600秒内，不需要再发送预检验请求，可以缓存该结果 */
    response.setHeader("Access-Control-Max-Age", age);
    /* 表明它允许跨域请求包含content-type头 */
    response.setHeader("Access-Control-Allow-Headers",headers);
    chain.doFilter(req, res);
  }

  public void init(FilterConfig filterConfig) {
    this.origin=filterConfig.getInitParameter("origin");
    this.methods=filterConfig.getInitParameter("methods");
    this.age=filterConfig.getInitParameter("age");
    this.headers=filterConfig.getInitParameter("headers");
  }

  public void destroy() {}
}
